<template>
  <div class="admin-management">
    <div class="page-header">
      <h2>管理员管理</h2>
      <el-button type="primary" @click="showAddDialog">添加管理员</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="超级管理员" value="super" />
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 管理员列表表格 -->
    <el-card>
      <el-table :data="adminList" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.role === 'super'" type="danger">超级管理员</el-tag>
            <el-tag v-else-if="row.role === 'admin'" type="warning">管理员</el-tag>
            <el-tag v-else-if="row.role === 'operator'" type="primary">操作员</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'active'" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="160" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="editAdmin(row)">编辑</el-button>
            <el-button type="warning" link @click="resetPassword(row)">重置密码</el-button>
            <el-button 
              v-if="row.status === 'active'" 
              type="danger" 
              link 
              @click="toggleStatus(row)"
            >
              禁用
            </el-button>
            <el-button 
              v-else 
              type="success" 
              link 
              @click="toggleStatus(row)"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑管理员对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加管理员' : '编辑管理员'" 
      width="600px"
    >
      <el-form :model="adminForm" :rules="formRules" ref="adminFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="adminForm.username" 
            placeholder="请输入用户名" 
            :disabled="dialogMode === 'edit'"
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="adminForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="adminForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item v-if="dialogMode === 'add'" label="密码" prop="password">
          <el-input 
            v-model="adminForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="adminForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="adminForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AdminManagement',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogMode = ref('add')
    const adminFormRef = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      username: '',
      role: '',
      status: ''
    })
    
    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 管理员表单
    const adminForm = reactive({
      username: '',
      realName: '',
      email: '',
      phone: '',
      password: '',
      role: 'admin',
      status: 'active',
      remark: ''
    })
    
    // 表单验证规则
    const formRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      role: [{ required: true, message: '请选择角色', trigger: 'change' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }
    
    // 管理员列表
    const adminList = ref([
      {
        id: 1,
        username: 'admin',
        realName: '系统管理员',
        email: 'admin@venue.com',
        phone: '13800138001',
        role: 'super',
        status: 'active',
        lastLogin: '2024-01-15 16:30:00',
        createdAt: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        username: 'manager',
        realName: '场馆经理',
        email: 'manager@venue.com',
        phone: '13800138002',
        role: 'admin',
        status: 'active',
        lastLogin: '2024-01-15 15:20:00',
        createdAt: '2024-01-02 14:30:00'
      }
    ])
    
    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        // 这里调用API加载管理员列表
        console.log('加载管理员列表数据')
        pagination.total = adminList.value.length
      } catch (error) {
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      loadData()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        username: '',
        role: '',
        status: ''
      })
      loadData()
    }
    
    // 显示添加对话框
    const showAddDialog = () => {
      dialogMode.value = 'add'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑管理员
    const editAdmin = (admin) => {
      dialogMode.value = 'edit'
      Object.assign(adminForm, admin)
      dialogVisible.value = true
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(adminForm, {
        username: '',
        realName: '',
        email: '',
        phone: '',
        password: '',
        role: 'admin',
        status: 'active',
        remark: ''
      })
      adminFormRef.value?.clearValidate()
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        await adminFormRef.value.validate()
        
        if (dialogMode.value === 'add') {
          // 这里调用添加API
          ElMessage.success('管理员添加成功')
        } else {
          // 这里调用编辑API
          ElMessage.success('管理员更新成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.log('表单验证失败')
      }
    }
    
    // 重置密码
    const resetPassword = async (admin) => {
      try {
        await ElMessageBox.confirm('确认要重置该管理员的密码吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 这里调用重置密码API
        ElMessage.success('密码重置成功，新密码已发送到管理员邮箱')
      } catch (error) {
        console.log('取消重置密码')
      }
    }
    
    // 切换状态
    const toggleStatus = async (admin) => {
      const action = admin.status === 'active' ? '禁用' : '启用'
      
      try {
        await ElMessageBox.confirm(`确认要${action}该管理员吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 这里调用状态切换API
        admin.status = admin.status === 'active' ? 'disabled' : 'active'
        ElMessage.success(`管理员${action}成功`)
      } catch (error) {
        console.log(`取消${action}`)
      }
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadData()
    }
    
    const handleCurrentChange = (page) => {
      pagination.page = page
      loadData()
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      searchForm,
      pagination,
      adminList,
      dialogVisible,
      dialogMode,
      adminForm,
      formRules,
      adminFormRef,
      handleSearch,
      resetSearch,
      showAddDialog,
      editAdmin,
      submitForm,
      resetPassword,
      toggleStatus,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    color: var(--text-color-primary);
    font-weight: 500;
  }
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 